import struct
import random
from datetime import datetime, timedelta
import os
import numpy as np
import xml.etree.ElementTree as ET
from xml.dom import minidom
from logger import logger

def generate_frame_data_xml(num_frames, output_file, error_rate=0.0):
    """生成XML格式的帧数据文件"""
    try:
        logger.info(f"开始生成帧数据文件: {output_file}")
        
        # 创建根元素
        root = ET.Element("frames")
        
        for i in range(num_frames):
            # 创建帧元素
            frame = ET.SubElement(root, "frame")
            frame.set("index", str(i))
            
            # 帧头 (固定值 0xEB90CDAB)
            header = ET.SubElement(frame, "sync_word")
            header.set("value", "0xEB90CDAB")
            header.set("type", "uint32")
            header.set("length", "4")
            
            # 帧计数
            frame_count = ET.SubElement(frame, "frame_count")
            frame_count.set("value", str(i))
            frame_count.set("type", "uint32")
            frame_count.set("length", "4")
            
            # 虚拟信道 (0-3)
            vc = ET.SubElement(frame, "virtual_channel")
            vc_value = random.randint(0, 3)
            vc.set("value", str(vc_value))
            vc.set("type", "uint8")
            vc.set("length", "1")
            
            # 译码状态 (0: 成功, 1: 失败, 2: 部分成功)
            status = ET.SubElement(frame, "decode_status")
            status_value = random.randint(0, 2)
            status.set("value", str(status_value))
            status.set("type", "uint8")
            status.set("length", "1")
            
            # 数据负载
            payload = ET.SubElement(frame, "payload")
            payload.set("type", "bytes")
            payload.set("length", "1024")
            
            # 生成负载数据
            payload_data = []
            for _ in range(1024):
                if random.random() < error_rate:
                    byte = random.randint(0, 255)
                else:
                    byte = 0x55  # 正常数据模式
                payload_data.append(format(byte, '02x'))
            
            payload.text = ' '.join(payload_data)
            
            if i % 100 == 0:
                logger.debug(f"已生成 {i} 帧")
        
        # 格式化XML并写入文件
        xml_str = minidom.parseString(ET.tostring(root)).toprettyxml(indent="    ")
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(xml_str)
        
        logger.info(f"成功生成帧数据文件: {output_file}")
        
    except Exception as e:
        logger.error(f"生成帧数据文件失败: {str(e)}", exc_info=True)
        raise

def generate_log_file(duration_hours, interval_seconds, output_file):
    """生成日志文件"""
    try:
        logger.info(f"开始生成日志文件: {output_file}")
        
        start_time = datetime.now()
        
        with open(output_file, 'w', encoding='utf-8') as f:
            current_time = start_time
            count = 0
            while (current_time - start_time).total_seconds() < duration_hours * 3600:
                # 生成Eb/N0值（范围：5-15 dB，带有随机波动）
                eb_n0 = 10 + random.uniform(-5, 5)
                
                # 生成天线俯仰角（范围：10-80度，缓慢变化）
                elevation = 45 + 35 * \
                           np.sin(2 * np.pi * (current_time - start_time).total_seconds() / (3600 * 2))
                
                # 写入日志条目
                log_entry = f"[{current_time.strftime('%Y-%m-%d %H:%M:%S')}] "
                log_entry += f"Eb/N0: {eb_n0:.2f} dB, "
                log_entry += f"天线俯仰角: {elevation:.2f}度\n"
                
                f.write(log_entry)
                current_time += timedelta(seconds=interval_seconds)
                
                count += 1
                if count % 100 == 0:
                    logger.debug(f"已生成 {count} 条日志记录")
        
        logger.info(f"成功生成日志文件: {output_file}")
        
    except Exception as e:
        logger.error(f"生成日志文件失败: {str(e)}", exc_info=True)
        raise

if __name__ == '__main__':
    try:
        # 创建测试数据目录
        os.makedirs('test_data', exist_ok=True)
        logger.info("创建测试数据目录")
        
        # 生成正常帧数据文件
        generate_frame_data_xml(
            num_frames=100,  # 减少帧数
            output_file='test_data/normal_frames.xml',
            error_rate=0.0
        )
        
        # 生成带错误的帧数据文件
        generate_frame_data_xml(
            num_frames=100,  # 减少帧数
            output_file='test_data/error_frames.xml',
            error_rate=0.01
        )
        
        # 生成日志文件
        generate_log_file(
            duration_hours=1,  # 减少持续时间
            interval_seconds=60,
            output_file='test_data/demodulator.log'
        )
        
        logger.info("测试数据生成完成！")
        print("测试数据生成完成！")
        print("生成的文件：")
        print("- test_data/normal_frames.xml（正常帧数据）")
        print("- test_data/error_frames.xml（带错误的帧数据）")
        print("- test_data/demodulator.log（解调器日志）")
        
    except Exception as e:
        logger.error(f"生成测试数据失败: {str(e)}", exc_info=True)
        print(f"生成测试数据失败: {str(e)}")
        raise 